# 自定义用户认证
import logging
import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from users import constants
from users.models import User

logger = logging.getLogger("django")
s = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)


def check_verify_email_token(token):
    """检验邮箱的token"""
    try:
        payload = s.loads(token)
    except BadData:
        # 假如过时了，会报错
        return None
    else:
        # 获取解析后的数据并返回
        user_id = payload.get('user_id')
        email = payload.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user


def generate_verify_email_url(user):
    """
    生成邮箱激活连接
    :param user 当前登录的用户
    """

    # 序列化数据
    data = {'user_id': user.id, 'email': user.email}
    token = s.dumps(data)
    logger.info(token)
    return '%s?token=%s' % (settings.EMAIL_VERIFY_URL, token.decode())


def get_user_by_account(account):
    """通过手机号或者密码查询user"""
    logger.info("启用了自定义验证用户功能")
    try:
        if re.match(r"^1[3-9]\d{9}$", account):
            # 判断为手机号则通过手机号查用户
            user = User.objects.get(mobile=account)
        else:
            # 判断为用户名则通过用户名查用户
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileBackend(ModelBackend):
    """自定义用户认证"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写用户认证的方法
        :param username 用户名或手机号
        :param password 密码
        :return user
        """
        user = get_user_by_account(username)
        if user and user.check_password(password):
            # 校验密码
            return user
        else:
            return None
